﻿using System;
using System.Collections.Generic;
using System.ServiceModel.DomainServices.Client;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using AppLab.Models;
using AppLab.Views.MobileBasicInfo;
using AppLab.Web;
using AppLab.Web.Services;
using AppLab.Data;

namespace AppLab.Views
{
    public partial class TerminalInfos : Page
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        FlowContext flow = new FlowContext();
        private MobileBasicInfoData mobileBasicInfoData = new MobileBasicInfoData();

        //选中DataGrid的记录行数，默认选中首行
        private int rowIndex = 0;
        // 控制每页DateGrid的行数
        private const int pageSize = 20;

        public TerminalInfos()
        {
            InitializeComponent();
            PageScrollViewer.SetIsMouseWheelScrollingEnabled(true);
            this.Title = ApplicationStrings.TerminalInfoPageTitle;
            this.DataContext = mobileBasicInfoData;
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            busyIndicatorLoad.IsBusy = true;
            autoCompleteBoxMbBrand.Focus();

            //绑定品牌下拉框、型号下拉值、DataGrid数据表
            BindComBoxOfBrand();
            BindAutoCompleteOfMobileType();
            BindGrid(-1, 0);
        }

        #region 分页处理，每次加载一页

        public void BindGrid(int brandID, int pageIndex)
        {
            LoadItemsSource(brandID, pageIndex, string.Empty);
        }

        private void BindGrid(string type, int pageIndex)
        {
            LoadItemsSource(-1, pageIndex, type);
        }

        private void LoadItemsSource(int brandID, int pageIndex, string type)
        {
            InvokeOperation<int> iCount = flow.GetMobileBasicInfoCount(brandID, type);
            iCount.Completed += new EventHandler(iCount_Completed);

            var temp = flow.GetMobileBasicInfoOnPageQuery(pageSize, pageIndex, brandID, type);
            LoadOperation<MobileBasicInfoData> loadMb = flow.Load(temp);
            loadMb.Completed += new EventHandler(loadMb_Completed);
        }

        void loadMb_Completed(object sender, EventArgs e)
        {
            LoadOperation loadMb = (LoadOperation)sender;
            dgPhoneInfo.ItemsSource = loadMb.Entities;
            dgPhoneInfo.SelectedIndex = rowIndex;

            busyIndicatorLoad.IsBusy = false;
        }

        void iCount_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if (dpPhoneInfo.PageIndex <= 0)
            {
                dpPhoneInfo.BindSource((int)(invokeOp.Value), pageSize);
                dpPhoneInfo.PageIndexChanged -= new EventHandler<EventArgs>(dpPhoneInfo_PageIndexChanged);
                dpPhoneInfo.PageIndexChanged += new EventHandler<EventArgs>(dpPhoneInfo_PageIndexChanged);
            }
        }

        private void dpPhoneInfo_PageIndexChanged(object sender, EventArgs e)
        {
            //左右换页时，默认让其选中第一行
            rowIndex = 0;
            if (mobileBrand.SelectedItem == null && string.IsNullOrEmpty(autoCompleteBoxMbBrand.Text))
            {
                BindGrid(-1, dpPhoneInfo.PageIndex);
            }
            else if (mobileBrand.SelectedItem != null)
            {
                BindGrid((mobileBrand.SelectedItem as Brand).BrandId, dpPhoneInfo.PageIndex);
            }
            else
            {
                BindGrid(autoCompleteBoxMbBrand.Text.Replace(" ", ""), dpPhoneInfo.PageIndex);
            }
        }

        #endregion

        #region 品牌下拉框

        private void BindComBoxOfBrand()
        {
            var query = flow.GetBrandsQuery();
            var loadBrand = flow.Load(query);
            loadBrand.Completed += new EventHandler(loadBrand_Completed);
        }

        void loadBrand_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            mobileBrand.ItemsSource = loadOp.Entities;
            mobileBrand.DisplayMemberPath = "BrandName";
        }

        //选择品牌事件
        private void mobileBrand_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (mobileBrand.SelectedItem != null)
            {
                this.autoCompleteBoxMbBrand.Text = string.Empty;
                this.dpPhoneInfo.PageIndex = 0;
                rowIndex = 0;
                BindGrid((mobileBrand.SelectedItem as Brand).BrandId, 0);
            }
        }
        #endregion

        #region AutoCompleteBox下拉
        //保存所有的手机型号
        private ComboBox comb = new ComboBox();
        private void BindAutoCompleteOfMobileType()
        {
            var query = flow.GetMobileTypesQuery(-1);

            LoadOperation<MobileType> load = flow.Load(query);
            load.Completed += new EventHandler(load_Completed);
        }

        void load_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            comb.ItemsSource = loadOp.Entities;
            BindAutoCompleteBox(comb);
        }

        private void BindAutoCompleteBox(ComboBox comb)
        {
            List<String> listStr = new List<string>();
            for (int i = 0; i < comb.Items.Count; i++)
            {
                MobileType e = comb.Items[i] as MobileType;
                listStr.Add(e.TypeName);
            }
            autoCompleteBoxMbBrand.ItemsSource = listStr;
        }

        private void autoCompleteBoxMbBrand_GotFocus(object sender, RoutedEventArgs e)
        {
            this.mobileBrand.SelectedItem = null;
        }
        #endregion

        #region 添加终端
        private void AddNewBrandMobile_Click(object sender, RoutedEventArgs e)
        {
            if (!WebContext.Current.User.IsAuthenticated)
                MessageBox.Show(PopupDialogStrings.MustBeLoggedInString, "未登录", MessageBoxButton.OK);
            else
            {
                MobileBasicInfoWindow addW = new MobileBasicInfoWindow(this.mobileBrand);
                addW.Closed += new EventHandler(addW_Closed);
                addW.Show();
            }
        }

        void addW_Closed(object sender, EventArgs e)
        {
            if ((bool)(sender as MobileBasicInfoWindow).DialogResult)
            {
                busyIndicatorLoad.IsBusy = true;
                MessageBox.Show(PopupDialogStrings.SuccessfullyAddedMobileInfo, "终端录入", MessageBoxButton.OK);

                this.mobileBrand.SelectedItem = null;
                this.autoCompleteBoxMbBrand.Text = string.Empty;
                this.dpPhoneInfo.PageIndex = 0;
                this.rowIndex = 0;
                BindGrid(-1, 0);
            }
        }
        #endregion

        #region 修改终端
        private void ModifyMobile_Click(object sender, RoutedEventArgs e)
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                MessageBox.Show(PopupDialogStrings.MustBeLoggedInString, "未登录", MessageBoxButton.OK);
            }
            else if (this.dgPhoneInfo.SelectedItem != null)
            {
                MobileBasicInfoWindow modifyW = new MobileBasicInfoWindow((MobileBasicInfoData)this.dgPhoneInfo.SelectedItem, this.mobileBrand);
                modifyW.Closed += new EventHandler(modifyW_Closed);
                modifyW.Show();
            }
            else
            {
                MessageBox.Show("未选择终端！", "终端", MessageBoxButton.OK);
            }
        }

        void modifyW_Closed(object sender, EventArgs e)
        {
            if ((bool)(sender as MobileBasicInfoWindow).DialogResult)
            {
                busyIndicatorLoad.IsBusy = true;
                MobileBasicInfoData emp = (MobileBasicInfoData)this.dgPhoneInfo.SelectedItem;
                MessageBox.Show("修改" + emp.MobileBrand + "(" + emp.MobileType + ")" + "成功！", "终端修改", MessageBoxButton.OK);

                if (mobileBrand.SelectedItem != null)
                {
                    BindGrid((mobileBrand.SelectedItem as Brand).BrandId, dpPhoneInfo.PageIndex);
                }
                else if (!string.IsNullOrEmpty(autoCompleteBoxMbBrand.Text.Replace(" ", "")))
                {
                    BindGrid(autoCompleteBoxMbBrand.Text.Replace(" ", ""), dpPhoneInfo.PageIndex);
                }
                else
                {
                    BindGrid(-1, dpPhoneInfo.PageIndex);
                }
            }
        }
        //双击修改终端
        private int dBClick = 0;
        private void dgPhoneInfo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            dBClick++;
            if (this.dgPhoneInfo.SelectedItem != null && rowIndex == this.dgPhoneInfo.SelectedIndex && dBClick > 1)
            {
                MobileBasicInfoWindow modifyW = new MobileBasicInfoWindow((MobileBasicInfoData)this.dgPhoneInfo.SelectedItem, this.mobileBrand);
                modifyW.Closed += new EventHandler(modifyW_Closed);
                modifyW.Show();
            }
        }

        #endregion

        private void dgPhoneInfo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.dgPhoneInfo.SelectedItem != null)
            {
                rowIndex = this.dgPhoneInfo.SelectedIndex;
                dBClick = 0;
            }
            else
            {
                rowIndex = 0;
            }
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            rowIndex = 0;
            this.dpPhoneInfo.PageIndex = 0;
            this.mobileBrand.SelectedItem = null;
            //AutoCompleteBox无值，表搜索全部终端
            if (string.IsNullOrEmpty(autoCompleteBoxMbBrand.Text.Replace(" ", "")))
            {
                BindGrid(-1, 0);
            }
            else
            {
                BindGrid(autoCompleteBoxMbBrand.Text.Replace(" ", ""), 0);
            }
        }
        //全部终端
        private void ShowAllMobileInfo_Click(object sender, RoutedEventArgs e)
        {
            this.mobileBrand.SelectedItem = null;
            this.autoCompleteBoxMbBrand.Text = string.Empty;
            this.dpPhoneInfo.PageIndex = 0;
            rowIndex = 0;
            BindGrid(-1, 0);
        }

        #region 适配状态

        private void ModifyAdaptation_Click(object sender, RoutedEventArgs e)
        {
            //if (!WebContext.Current.User.IsAuthenticated)
            //{
            //    MessageBox.Show(PopupDialogStrings.MustBeLoggedInString, "未登录", MessageBoxButton.OK);
            //}
            //else if (this.dgPhoneInfo.SelectedItem != null)
            //{
            //    MobileBasicInfoData mobile = this.dgPhoneInfo.SelectedItem as MobileBasicInfoData;
            //    Adaptation adapt = new Adaptation(mobile.MobileType, mobile.MobileID);
            //    adapt.Show();
            //}
        }

        #endregion
    }
}
